<?php
class ControllerDb extends Controller {
	public function __construct($q) {
		parent::__construct($q);
	}
	
	public function execute() {
		$v = mb_strtolower($this->getQuery());

		if(empty($v))
			return $this->doHelp();

		$c = 'do'.ucfirst($v);
		if(method_exists($this, $c))
			$this->$c();
		else
			throw new SignalArgUnknown($v);
	}

	private function doHelp() {
		View::show("Usage : db command [options]");
	}
	
	private function doList() {
		if(!ModelUser::getInstance())
			return View::show("[-] You are not logged in");

		
		while($v = $this->getQuery())
			echo "\t- $v\n";
		
		return;
		
		
		
		View::show("[+] List of DataBases");
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,
				"https://clients.1and1.fr/xml/config/DBMySQLOverview;jsessionid=".ModelConfig::get('sessionid'));
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_COOKIEJAR, ModelConfig::get('cookie'));
		curl_setopt($ch, CURLOPT_COOKIEFILE, ModelConfig::get('cookie'));
		$init = curl_exec($ch);

		preg_match_all('#<tr class="(?:low|high)"><td>db([0-9]+)</td><td>dbo([a-z0-9]+)</td><td>([a-z0-9.]+)</td><td>([^<]+)</td><td>([^<]+)</td>.+;selected=([0-9]+)#sU', $init, $m, PREG_SET_ORDER);
		foreach($m as $v)
			View::show("\t[+] ({$v[6]}) {$v[1]} {$v[2]} {$v[3]} {$v[4]}");
	}
	
	private function doAdd() {
		if(!ModelUser::getInstance())
			return View::show("[-] You are not logged in");

		$pwd = ModelPassword::generate();
		$dsc = 'default';
		// TODO handle options

		View::show("[+] Adding a Database");
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,
				"https://clients.1and1.fr/xml/config/DBMySQLPrepareCreate;jsessionid=".ModelConfig::get('sessionid'));
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_COOKIEJAR, ModelConfig::get('cookie'));
		curl_setopt($ch, CURLOPT_COOKIEFILE, ModelConfig::get('cookie'));
		curl_setopt($ch, CURLOPT_POSTFIELDS, array(
				'__lf'				=> 'dbMySQLCreateDBFlow',
				'__sendingdata'		=> '1',
				'data.Description'	=> $dsc,
				'data.Password1'	=> $pwd,
				'data.Password2'	=> $pwd));
		$init = curl_exec($ch);
	
		preg_match_all('#<td class="error">(.+)</td>#sU', $init, $m, PREG_SET_ORDER);
		if(empty($m)) {
			preg_match('#<td><span>db([0-9]+)</span>#', $init, $M);
			if(empty($M)) {
				echo "ERROR BIATCH";
				echo $init;
			} else
				View::show("\t[+] Database (db{$M[1]}) added, password is '$pwd'");
		} else
			foreach($m as $v)
				View::show("\t[-] Error : {$v[1]}");
	}
}